import { defineStore } from "pinia";
import { ref, reactive } from "vue";
import useUserStore from "@/store/modules/user/index.js";

const storedToken = uni.getStorageSync("token");
export const useTokenStore = defineStore("token", {
  state: () => ({
    token: reactive(storedToken || {}),
  }),
  actions: {
    getCookie(key) {
      const data = uni.getStorageSync(key);
      if (!data || !data.value) {
        return null; // 数据不存在或已过期
      }
      const now = new Date().getTime();
      console.log("过期？", now > data.expireTime);
      if (now > data.expireTime) {
        // 数据已过期，清除数据
        uni.removeStorageSync(key);
        syncToken();
        return null;
      }
      return data.value; // 返回token值
    },
    setCookie(key, value, expiresInSeconds) {
      const now = new Date().getTime();
      const expireTime = now + expiresInSeconds * 1000; // 将秒转换为毫秒
      // 存储token和过期时间
      uni.setStorageSync(key, {
        value,
        expireTime,
      });
    },
    syncToken() {
      const storedToken = uni.getStorageSync("token") || {};
      this.token = reactive(storedToken);
      if (!this.token || !this.token.value) {
        // 检测token是否为空，为空则弹出登录框
        const userStore = useUserStore();
        userStore.resetUserInfoAndTenant();
        userStore.isLogin.value = 0;
        userStore.isLogin.popShow = true;
      }
    },
  },
  getters: {
    getToken: (state) => {
      if (state.token && state.token.value) {
        return state.token.value;
      }
      return "";
    },
  },
});
